library(xtable)
library(Amelia)

load('imputed_data.Rdata')
source('colnames2labels.R')

balance.vars <- c('accused_female','criminal_record','Prison_term_M','methodGuilty','methodTrial','offense1','offense2','offense3','offense4','victimRace2','prequest2','appellant1','appellant2','avg_jage','avg_jexp', 'female_j')

##################### make Table 9 ###################
mybal <- matrix(nrow = 0, ncol = 4)
colnames(mybal) <- c('Pred.Mixed','Pred.AllJewish','Diff','P-val')
for(varname in balance.vars){
	meld.in <- matrix(nrow = n.impute, ncol = 4)
	my.form <- paste(varname, '~ narabs_J + court_Jerusalem + court_Nazareth')
	for(i in c(1:n.impute)){
		#for each imputed dataset, regress each variable against mixed panel and court effects
		my.dat <- a.out$imputations[[i]]
		#Arab defendants
		my.dat <- my.dat[my.dat$accused_arab == 1,]
		cur.model <- lm(as.formula(my.form), data = my.dat)
		newdata <- list(c(1,0),c(FALSE,FALSE),c(FALSE,FALSE))
		names(newdata) <- c('narabs_J', 'court_Jerusalem','court_Nazareth')
		meld.in[i,] <- c(predict(cur.model, newdata), summary(cur.model)$coefficients[2,c(1,4)])	
	}
	melded.vals <- mi.meld(q = meld.in, se = matrix(0, nrow = n.impute, ncol = 4))$q.mi
	mybal <- rbind(mybal, melded.vals)
}
rownames(mybal) <- balance.vars

print("TABLE 9")
print(xtable(names2labels(names2labels(mybal), col.or.row = 'row')))

##################### make Table 10 ###################
mybal <- matrix(nrow = 0, ncol = 4)
colnames(mybal) <- c('Pred.Mixed','Pred.AllJewish','Diff','P-val')
for(varname in balance.vars){
	meld.in <- matrix(nrow = n.impute, ncol = 4)
	my.form <- paste(varname, '~ narabs_J + court_Jerusalem + court_Nazareth')
	for(i in c(1:n.impute)){
		#for each imputed dataset, regress each variable against mixed panel and court effects
		my.dat <- a.out$imputations[[i]]
		#Jewish defendants
		my.dat <- my.dat[my.dat$accused_arab == 0,]
		cur.model <- lm(as.formula(my.form), data = my.dat)
		newdata <- list(c(1,0),c(FALSE,FALSE),c(FALSE,FALSE))
		names(newdata) <- c('narabs_J', 'court_Jerusalem','court_Nazareth')
		meld.in[i,] <- c(predict(cur.model, newdata), summary(cur.model)$coefficients[2,c(1,4)])	
	}
	melded.vals <- mi.meld(q = meld.in, se = matrix(0, nrow = n.impute, ncol = 4))$q.mi
	mybal <- rbind(mybal, melded.vals)
}
rownames(mybal) <- balance.vars

print("TABLE 10")
print(xtable(names2labels(names2labels(mybal), col.or.row = 'row')))